package com.steakliu.sun.serializer;

import com.steakliu.sun.serializer.api.SunSerializer;
import com.steakliu.sun.spi.annotation.Join;
import org.apache.commons.lang3.ObjectUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 功能说明： JDK序列化器
 * <p>
 * Original @Author: steakliu-刘牌, 2023-01-08  13:12
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
@Join
public class JdkSerializer implements SunSerializer {
    @Override
    public <T> byte[] serialize(T obj) {
        if (ObjectUtils.isEmpty(obj)){
            throw new RuntimeException("Serialized object cannot be empty");
        }
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bo);
            os.writeObject(obj);
            return bo.toByteArray();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (ObjectUtils.isEmpty(bytes)){
            throw new RuntimeException("Serialized object cannot be empty!");
        }
        try {
            ByteArrayInputStream bs = new ByteArrayInputStream(bytes);
            ObjectInputStream inputStream = new ObjectInputStream(bs);
            return (T) inputStream.readObject();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
